<%--
  Created by IntelliJ IDEA.
  User: 孤焰
  Date: 2021/5/24
  Time: 16:17
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>商品列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layuiadmin/style/admin.css" media="all">
    <style>
        .layui-dropdown{
            height: 300px;
            overflow: auto;
        }
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <button class="layui-btn" id="product-category" style="position: relative">
                        商品分类
                        <i class="layui-icon layui-icon-down layui-font-12" style="right: 0"></i>
                    </button>

                    <%-- 搜索框--%>
                    <form class="layui-form" style="display: inline-block;margin-left: 70px">
                        <div class="layui-inline">
                                <input type="text" name="search" placeholder="搜索商品名称" autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-inline">
                                <button class="layui-btn" lay-submit="" lay-filter="search">搜索</button>
                        </div>
                    </form>

                </div>
                <div class="layui-card-body">
                    <table class="layui-hide" id="product-list" lay-filter="product-list"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="${pageContext.request.contextPath}/layuiadmin/layui/layui.js"></script>
<script src="${pageContext.request.contextPath}/static/js/axios.min.js"></script>
<script>
    layui.config({
        base: '${pageContext.request.contextPath}/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table', 'form', 'layer', 'dropdown'], function(){
        var admin = layui.admin
        var table = layui.table;
        var form = layui.form;
        var dropdown = layui.dropdown;

        var tableWhere = {};
        table.render({
            id: 'productList',
            elem: '#product-list',
            url: '${pageContext.request.contextPath}/product/productList',
            where: tableWhere,
            cols: [[
                {type: 'checkbox'},
                {
                    title: '类别',
                    templet: function (data) {
                        return data.category.name;
                    },
                    width: 114
                },
                {title: '商品名称', field:'name'},
                {
                    title: '主图',
                    templet: function (data) {
                        console.log('${pageContext.request.contextPath}');
                        return '<div><img src="${pageContext.request.contextPath}' + data.mainImage + '"></div>'
                    }
                },
                {title: '商品副标题', field:'subtitle'},
                {title: '价格', field:'price', width: 96, sort: true, edit: 'text'},
                {title: '库存数量', field:'stock', width: 120, sort: true, edit: 'text'},
                {
                    title: '状态',
                    templet: function (data) {
                        if (data.status == 1) {
                            return '<div><input type="checkbox" lay-filter="status" product-id="'+data.id+'" lay-skin="switch" lay-text="在售|下架" checked></div>';
                        } else {
                            return '<div><input type="checkbox" lay-filter="status" product-id="'+data.id+'" lay-skin="switch" lay-text="在售|下架"></div>';
                        }
                    },
                    width: 96
                }
            ]],
            page: true,
            toolbar: 'default'
        });

        axios.get('${pageContext.request.contextPath}/category/categoryLeafList').then(function (res) {
            var categoryList = [];
            categoryList.push({
                title: '全部类别',
                id: null
            });
            for (var i = 0; i < res.data.data.length; i++) {
                var category = res.data.data[i];
                categoryList.push({
                    title: category.name,
                    id: category.id
                });
            }

            //下拉菜单渲染
            dropdown.render({
                elem: '#product-category',
                data: categoryList,
                trigger: 'hover',
                //菜单被点击事件
                click: function(obj){
                    tableWhere.categoryId = obj.id;
                    table.reload('productList');
                }
            });
        });

        //监听表单
        form.on('switch(status)', function (data) {
            var productId = data.elem.getAttribute('product-id');
            var productStatus = data.elem.checked ? 1 : 2;

            var params = {
                id: productId,
                status: productStatus
            };

            axios.post('${pageContext.request.contextPath}/product/updateProductById', params).then(function (res) {
                if (res.data.code == 200) {
                    layer.msg('商品状态已更新', {icon: 6});
                } else {
                    layer.msg('商品状态修改失败', {icon: 5});
                }

            });
        });

        //监听搜索表单
        form.on('submit(search)', function (data) {
            tableWhere.search = data.field.search;
            table.reload('productList');
            return false;
        });

        //监听单元格编辑
        table.on('edit(product-list)', function (obj) {
            var id = obj.data.id;
            var price = obj.data.price;
            var stock = obj.data.stock;

            //价格正则校验
            var priceReg = /(^[1-9][0-9]{0,7}$)|(^((0\.0[1-9]$)|(^0\.[1-9]\d?)$)|(^[1-9][0-9]{0,7}\.\d{1,2})$)/;
            //正整数正则校验
            var stockReg = /^[1-9]\d*$/;
            if (priceReg.test(price) && stockReg.test(stock)) {
                var param = {
                    id: id,
                    price: price,
                    stock: stock
                }

                axios.post('${pageContext.request.contextPath}/product/updateProductById', param).then(function (res){
                    if (res.data.code == 200) {
                        layer.msg('修改成功', {icon: 6});
                    } else {
                        layer.msg('修改失败', {icon: 5});
                    }

                });
            } else {
                layer.msg("值不合法", {icon: 5});
                // TODO 提示完不合法之后单元格没有恢复正确值
            }
        });

        //单元格表头工具栏监听
        table.on('toolbar(product-list)', function(obj) {
            switch (obj.event) {
                case 'add':
                    top.layui.index.openTabsPage('${pageContext.request.contextPath}/product/productAdd', "商品增加");
                    break;
                case 'delete':
                    var checkBoxData = table.checkStatus('productList').data;
                    if (checkBoxData.length == 0) {
                        layer.msg('未选中数据项', {icon: 5});
                        return;
                    }

                    layer.confirm('你确认删除吗?', {title:'提示'}, function(index){
                        var idArr = [];
                        for (var i = 0; i < checkBoxData.length; i++) {
                            idArr.push(checkBoxData[i].id);
                        }

                        axios.post('${pageContext.request.contextPath}/product/batchDelProduct', idArr).then(function (res) {
                            if (res.data.code != 200) {
                                layer.msg('数据库遇到未知错误，删除失败', {icon: 5});
                            } else {
                                layer.msg('数据删除成功', {icon: 6});
                                table.reload('productList');
                            }
                        });

                        layer.close(index);
                    });
                    break;
                case 'update':
                    var checkBoxData = table.checkStatus('productList').data;
                    if (checkBoxData.length == 0) {
                        layer.msg('未选中数据项', {icon: 5});
                        return;
                    }
                    if (checkBoxData.length > 1) {
                        layer.msg('数据项不可以多选', {icon: 5});
                        return;
                    }

                    layer.open({
                        type: 2,
                        title: '商品编辑',
                        shadeClose: false,
                        shade: 0,
                        area: ['60%', '90%'],
                        content: '${pageContext.request.contextPath}/product/productUpdate?id='+checkBoxData[0].id //iframe的url
                    });
                    break;
            }
        });
    });
</script>
</body>
</html>